#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年4月22日

@author: Administrator
'''
from article import settings
from article.models import Article
from celery import task
from common.decorators.celery import task_exception_handler
from common.utils.storage import exists, save_url_by_fpath, get_absolute_url
from elasticsearch.exceptions import TransportError
import logging
import re
from common.utils import es
from common.core.contenttypes import fetch_content_type_id
from django.contrib.auth.models import User

# 为loggers中定义的名称
logger = logging.getLogger("celery")

@task
@task_exception_handler
def update_article_img_src_task(article_id, content):
    '''
    function: 
    '''
    pat = '<img src="(.*?)"'
    reslists = re.findall(pat, content, re.M)
    for img_src in reslists:
        fname = img_src[img_src.rfind("/") + 1:]
        fpath = "%s%s/%s" % (settings.ARTICLE_MEDIA_PATH, article_id, fname)
        if not  exists(fpath):
            save_url_by_fpath(img_src, fpath)
        absolute_url = get_absolute_url(fpath)
        content = content.replace(img_src, absolute_url)
    #有图片才修改
    if reslists:
        Article.objects.filter(id=article_id).update(content=content)
        
@task
@task_exception_handler
def update_article_to_es_task(action):
    '''
    function: 
    '''
    #定义es
    try:
        es.es_client.index(settings.ES_INDEX_ARTICLE_LIST, doc_type=settings.ES_INDEX_ARTICLE_LIST_TYPE, body=action, id=action["id"])
        logger.info(u"update article to es by id %s success;" % action["id"]) 
    except TransportError:
        logger.warning(u"update article to es by id %s faild;" % action["id"])
        #日志记录 
        content_type = fetch_content_type_id("article", 'article')
        error_remark = u"同步文章到es by id %s" % action["id"]
        user = User.objects.get(username=settings.DEFAULT_COMMAND_USER)
        Logging.objects.create(user=user, state=1, content_type_id=content_type, object_id=action["id"], remark=error_remark, content=action)


